package com.dc.server.service.impl;

import com.dc.server.entity.OrdersEntity;
import com.dc.server.service.IDelayedOrdersService;
import com.dc.server.service.OrdersService;
import com.dc.server.threadpool.ThreadPoolManager;
import com.dc.server.vo.ItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.DelayQueue;

/**
 * @Auther: 赵聪
 * @Date: 2018/8/20 0020 22:17
 * @Description: 用阻塞队列来延时订单
 */
@Service
public class IDelayedOrdersImpl implements IDelayedOrdersService {
    @Autowired
    private OrdersService ordersService;

    private static DelayQueue<ItemVo<OrdersEntity>> delayOrder = new DelayQueue<>();

    @Override
    public void orderDelay(OrdersEntity ordersEntity, Long expireTime) {
        ItemVo<OrdersEntity> itemVo = new ItemVo<>(expireTime * 1000, ordersEntity);
        delayOrder.put(itemVo);
        System.out.println("订单超时时常" + expireTime + "被推入本地堆" + ordersEntity);
    }

    private class TaskOrders implements Runnable {
        private OrdersService ordersService;

        public TaskOrders(OrdersService ordersService) {
            this.ordersService = ordersService;
        }

        @Override
        public void run() {

            try {
                System.out.println("============================="+delayOrder.size());
                ItemVo<OrdersEntity> take = delayOrder.take();
                if (null != take) {
                    //TODO 更新数据库状态
                    ordersService.checkOrderStatus(take.getData());
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }



    @PostConstruct
    public void init() {
        System.out.println("======初始化====================");
        ThreadPoolManager.getInstance().execute(new TaskOrders(ordersService));
    }

}
